<script setup>
import { onMounted, ref } from 'vue'
import { upload } from '@/api/file'
import { addVehicle, modifyVehicleApi } from '@/api/vehicle'
import { getCampusListApi } from '@/api/campusOrShop'
import { getVehicleCategoryListApi, getBrandListApi } from '@/api/category'
import { getVehicleDetailsApi } from '@/api/vehicle'
import { useRouter, useRoute } from 'vue-router'
const router = useRouter()
const route = useRoute()

// 获取车辆分类、品牌、学校数据，用于下拉列表
const vehicleCategoryList = ref([])
const setVehicleCategoryList = async () => {
  const res = await getVehicleCategoryListApi()
  vehicleCategoryList.value = res.data
}

// 品牌选择器
const brandList = ref([])
// 车辆类型下拉菜单改变时的回调
const vehicleCategoryChange = async (value) => {
  const res = await getBrandListApi(value)
  brandList.value = res.data
  brandList.value.push({ id: 0, name: '其他' })
}

// 校园列表
const campusList = ref([])
const setCampusList = async () => {
  const res = await getCampusListApi()
  campusList.value = res.data
  campusList.value.push({ id: 0, name: '其他' })
}

// 交易地址单选框
const tradingAddr = ref(1)
const tradingAddrChange = (value) => {
  if (value === 1) {
    dataForm.value.vehicleMarket.campusOrShopId = ''
  } else {
    dataForm.value.vehicleMarket.tradeAddr = ''
  }
}

// 提交给后端的表单数据
const dataForm = ref({
  name: '',
  brand: '',
  registerDate: '',
  version: '',
  color: '',
  emissionStandard: '',
  vehicleMarket: {
    currentPrice: '',
    telNum: '',
    city: '',
    mileage: '',
    frontPic: '',
    campusOrShopId: '',
    tradeAddr: '',
    orderPrice: '',
    mainPictures: '',
    leaveMessage: '',
    vehicleCategoryId: '',
    brandId: '',
    transferNum: 0
  }
})
// 如果是修改页则回显数据
const setFormData = async () => {
  const res = await getVehicleDetailsApi(route.params.id)
  dataForm.value = res.data
  // 回显文件列表
  JSON.parse(dataForm.value.vehicleMarket.mainPictures).forEach((e) => {
    fileList.value.push({ url: e })
  })

  // 回显品牌分类
  vehicleCategoryChange(dataForm.value.vehicleMarket.vehicleCategoryId)

  // 回显交易地址/学校
  if (dataForm.value.vehicleMarket.campusOrShopId) {
    console.log(111)
    tradingAddr.value = 2
  }
}

// 表单校验规则
const rule1 = ref({
  brandId: [{ required: true, message: '请选择品牌', trigger: 'blur' }],
  vehicleCategoryId: [
    { required: true, message: '请选择分类', trigger: 'blur' }
  ]
})
const rule2 = ref({
  name: [{ required: true, message: '请输入车辆名称', trigger: 'blur' }],
  brand: [{ required: true, message: '请输入品牌名称', trigger: 'blur' }],
  color: [{ required: true, message: '请输入车身颜色', trigger: 'blur' }],
  registerDate: [{ required: true, message: '请输入购车时间', trigger: 'blur' }]
})
const rule3 = ref({
  city: [{ required: true, message: '请输入所在城市', trigger: 'blur' }],
  telNum: [{ required: true, message: '请输入联系方式', trigger: 'blur' }],
  mileage: [{ required: true, message: '请输入表显里程', trigger: 'blur' }],
  currentPrice: [{ required: true, message: '请输入价格', trigger: 'blur' }],
  tradeAddr: [{ required: true, message: '请输入交易地址', trigger: 'blur' }],
  orderPrice: [{ required: true, message: '请输入订金', trigger: 'blur' }],
  campusOrShopId: [{ required: true, message: '请选择学校', trigger: 'blur' }],
  frontPic: [{ required: true, message: '请上传车辆封面图', trigger: 'blur' }],
  mainPictures: [
    {
      validator: (rule, value, callback) => {
        if (fileList.value.length <= 0) {
          callback(new Error('请至少上传一张详细图片'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})

// 图片格式、大小校验
const beforeAvatarUpload = (rawFile) => {
  if (!['image/jpeg', 'image/jpg', 'image/png'].includes(rawFile.type)) {
    // eslint-disable-next-line no-undef
    ElMessage.error('仅支持上传jpeg、jpg、png格式的图片')
    return false
  } else if (rawFile.size / 1024 / 1024 > 5) {
    // eslint-disable-next-line no-undef
    ElMessage.error('请上传小于5M的图片')
    return false
  }
  return true
}

// 上传图片方法，返回图片url
const uploadImage = (file) => {
  const formData = new FormData()
  formData.append('file', file)
  return upload(formData)
}

// 上传封面图片
const frontPicUpload = async (uploadFile) => {
  const res = await uploadImage(uploadFile.file)
  dataForm.value.vehicleMarket.frontPic = res.data
}

// 上传详细图片
const fileList = ref([])
const uploadMainPics = async (uploadFile) => {
  const res = await uploadImage(uploadFile.file)
  fileList.value[fileList.value.length - 1].url = res.data
}
// 图片放大对话框
const dialogImageUrl = ref('')
const dialogVisible = ref(false)

// 删除图片
const handleRemove = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
}

// 预览图片
const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  dialogVisible.value = true
}

const form1 = ref(null)
const form2 = ref(null)
const form3 = ref(null)
// 提交表单
const submit = () => {
  form1.value.validate((isOk) => {
    if (isOk) {
      form2.value.validate((isOk) => {
        if (isOk) {
          form3.value.validate(async (isOk) => {
            if (isOk) {
              // 将fileList的url映射到dataForm相应属性中
              dataForm.value.vehicleMarket.mainPictures = JSON.stringify(
                fileList.value.map((e) => e.url)
              )
              if (route.params.id) {
                // 修改车辆
                await modifyVehicleApi(dataForm.value)
                // eslint-disable-next-line no-undef
                ElMessage.success('修改成功')
              } else {
                // 添加车辆
                await addVehicle(dataForm.value)
                // eslint-disable-next-line no-undef
                ElMessage.success('添加成功')
              }
              // 跳转到发布页
              router.replace('/member/publish')
            } else {
              form3.value.$el.scrollIntoView({ behavior: 'smooth' })
            }
          })
        } else {
          form2.value.$el.scrollIntoView({ behavior: 'smooth' })
        }
      })
    } else {
      form1.value.$el.scrollIntoView({ behavior: 'smooth' })
    }
  })
}

onMounted(() => {
  // 获取车辆分类列表，用于下拉菜单
  setVehicleCategoryList()
  // 获取校园列表，用于下拉菜单
  setCampusList()
  // 如果是修改页则回显数据
  if (route.params.id) {
    setFormData()
  }
})
</script>

<template>
  <div class="container">
    <div class="left">
      <el-affix :offset="60">
        <el-anchor :offset="10" style="width: 175px; padding: 20px 10px">
          <el-anchor-link :href="`#session1`"> 分类与品牌 </el-anchor-link>
          <el-anchor-link :href="`#session2`"> 基本信息 </el-anchor-link>
          <el-anchor-link :href="`#session3`"> 营销信息 </el-anchor-link>
          <el-anchor-link :href="`#session4`"> 车辆照片 </el-anchor-link>
        </el-anchor>
      </el-affix>
    </div>
    <div class="right">
      <div id="session1" class="header-desc">
        <span>分类与品牌</span>
      </div>
      <el-form
        ref="form1"
        :rules="rule1"
        :model="dataForm.vehicleMarket"
        label-width="140px"
        label-position="right"
      >
        <el-form-item prop="vehicleCategoryId" label="分类">
          <el-select
            v-model="dataForm.vehicleMarket.vehicleCategoryId"
            placeholder="请选择车辆类型"
            style="width: 160px"
            @change="vehicleCategoryChange"
          >
            <el-option
              v-for="item in vehicleCategoryList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="brandId" label="品牌">
          <el-select
            v-model="dataForm.vehicleMarket.brandId"
            placeholder="请选择品牌"
            style="width: 160px"
          >
            <el-option
              v-for="item in brandList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div id="session2" class="header-desc">
        <span>基本信息</span>
      </div>
      <el-form
        ref="form2"
        :rules="rule2"
        :model="dataForm"
        label-width="140px"
        label-position="right"
      >
        <el-form-item label="车辆名称" prop="name">
          <el-input style="width: 220px" v-model="dataForm.name" />
        </el-form-item>
        <el-form-item label="品牌名" prop="brand">
          <el-input style="width: 220px" v-model="dataForm.brand" />
        </el-form-item>
        <el-form-item label="购买时间" prop="registerDate">
          <el-date-picker
            v-model="dataForm.registerDate"
            type="month"
            placeholder="请选择购买时间"
            format="YYYY-MM"
            value-format="YYYY-MM"
          />
        </el-form-item>
        <el-form-item label="配置版本">
          <el-input style="width: 220px" v-model="dataForm.version" />
        </el-form-item>
        <el-form-item label="车身颜色" porp="color">
          <el-input style="width: 220px" v-model="dataForm.color" />
        </el-form-item>
        <el-form-item label="排放标准">
          <el-select
            v-model="dataForm.emissionStandard"
            placeholder="请选择排放标准"
            style="width: 220px"
            clearable
          >
            <el-option value="国I" />
            <el-option value="国II" />
            <el-option value="国III" />
            <el-option value="国IV" />
            <el-option value="国V" />
            <el-option value="国VI" />
          </el-select>
        </el-form-item>
      </el-form>
      <div id="session3" class="header-desc">
        <span>营销信息</span>
      </div>
      <el-form
        ref="form3"
        :rules="rule3"
        :model="dataForm.vehicleMarket"
        label-width="140px"
        label-position="right"
      >
        <el-form-item label="价格" prop="currentPrice">
          <el-input
            style="width: 220px"
            v-model="dataForm.vehicleMarket.currentPrice"
          />
        </el-form-item>
        <el-form-item label="订金" prop="orderPrice">
          <el-input
            style="width: 220px"
            v-model="dataForm.vehicleMarket.orderPrice"
          />
        </el-form-item>
        <el-form-item label="所在城市" prop="city">
          <el-input
            style="width: 220px"
            v-model="dataForm.vehicleMarket.city"
          />
        </el-form-item>
        <el-form-item label="联系电话" prop="telNum">
          <el-input
            style="width: 220px"
            v-model="dataForm.vehicleMarket.telNum"
          />
        </el-form-item>
        <el-form-item label="表显里程" prop="mileage">
          <el-input
            style="width: 220px"
            v-model="dataForm.vehicleMarket.mileage"
          />
        </el-form-item>
        <el-form-item label="过户次数" prop="mileage">
          <el-input-number
            v-model="dataForm.vehicleMarket.transferNum"
            :min="0"
            :max="10"
            controls-position="right"
          />
        </el-form-item>
        <el-form-item label="交易地点">
          <el-radio-group
            v-model="tradingAddr"
            class="ml-4"
            @change="tradingAddrChange"
          >
            <el-radio :value="1">校外</el-radio>
            <el-radio :value="2">学校</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="tradingAddr === 1" prop="tradeAddr">
          <el-input
            v-model="dataForm.vehicleMarket.tradeAddr"
            type="textarea"
            :rows="3"
            style="width: 260px"
            placeholder="请输入交易地址"
          ></el-input>
        </el-form-item>
        <el-form-item v-else prop="campusOrShopId">
          <el-select
            v-model="dataForm.vehicleMarket.campusOrShopId"
            placeholder="请选择学校"
            style="width: 160px"
          >
            <el-option
              v-for="item in campusList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注/留言">
          <el-input
            v-model="dataForm.vehicleMarket.leaveMessage"
            type="textarea"
            :rows="3"
            style="width: 260px"
            placeholder="请输入留言/说明"
          ></el-input>
        </el-form-item>
        <div id="session4" class="header-desc">
          <span>车辆照片</span>
        </div>
        <el-form-item label="封面照片" prop="frontPic">
          <el-upload
            class="avatar-uploader"
            :class="{
              'border-none': dataForm.vehicleMarket.frontPic
            }"
            action=""
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :http-request="frontPicUpload"
          >
            <img
              v-if="dataForm.vehicleMarket.frontPic"
              :src="dataForm.vehicleMarket.frontPic"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><i-ep-Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="详细照片" prop="mainPictures">
          <el-upload
            v-model:file-list="fileList"
            action=""
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :before-upload="beforeAvatarUpload"
            :http-request="uploadMainPics"
          >
            <el-icon><i-ep-Plus /></el-icon>
          </el-upload>

          <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
          </el-dialog>
        </el-form-item>
      </el-form>
      <div style="margin-left: 400px">
        <el-button size="large" type="primary" @click="submit">确定</el-button>
        <el-button size="large" @click="router.replace('/')">取消</el-button>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.header-desc {
  border-bottom: 1px solid #ddd;
  padding: 15px 30px;
  margin-bottom: 25px;
  background-color: #fff;
}
.container {
  display: flex;
  padding: 20px 0;

  .right {
    background-color: #fff;
    flex: 1;
    margin-left: 50px;
    padding-bottom: 100px;
  }
}

.avatar-uploader {
  border: 1px dashed var(--el-border-color);
  .avatar {
    max-width: 150px;
    height: auto;
  }
  .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }
  &:hover {
    border-color: var(--el-color-primary);
  }

  &.border-none {
    border: 0px;
  }
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
